package cn.mcch.investigator.model;

import java.util.Map;

import cn.mcch.investigator.listener.OnResponseListener;
import cn.mcch.investigator.model.bean.ResponseBean;
import cn.mcch.investigator.utils.JsonUtils;
import cn.mcch.investigator.utils.L;
import cn.mcch.investigator.utils.ToastUtils;

public class BaseModel {

    private BaseRequest baseRequest;
    private OnResponseListener l;

    public void request(int id, String service, Map<String, String> params, final OnResponseListener listener) {
        this.l = listener;
        if (baseRequest == null) {
            baseRequest = new BaseRequest() {

                @Override
                public void onResponse(String json, int id) {

                    ResponseBean responseBean = JsonUtils.fromJsonToObject(json, ResponseBean.class);
                    if (responseBean.status) {
                        L.e(responseBean.data);
                        result = true;
                        if (l != null) {
                            l.onSuccess(responseBean.data, id);
                        }
                    } else {
                        result = false;
                        ToastUtils.showToast(responseBean.msg);
                    }

                }

                @Override
                public void onBefore(int id) {
                    if (l != null) {
                        l.onBefore(id);
                    }

                }

                @Override
                public void onAfter(boolean result, int id) {
                    if (l != null) {
                        l.onAfter(result, id);
                    }

                }
            };
        }
        baseRequest.request(id, service, params);
    }

    /**
     * 取消掉网络请求
     */
    public void cancelTag() {
        if (baseRequest != null) {
            baseRequest.cancelTag();
            baseRequest = null;
        }
    }

}
